/*
 * @Author: your name
 * @Date: 2022-03-29 22:39:39
 * @LastEditTime: 2022-04-29 11:16:17
 * @LastEditors: Please set LastEditors
 * @Description: register 注册用户
 * @FilePath: \blog-api\src\user\user.service.ts
 */

import { User } from './entities/user.entity';
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto, UserDto, LoginDto } from './dto/create-user.dto';
import { Repository } from 'typeorm';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private JwtService: JwtService,
  ) {}
  
  // 注册
  async create(createUser: CreateUserDto) {
    const { user_tel } = createUser;

    const existUser = await this.userRepository.findOne({
      where: { user_tel },
    });
    if(existUser){
      throw new HttpException("手机号重复", HttpStatus.BAD_REQUEST);
    }

    const newUser = await this.userRepository.create(createUser);
    newUser.user_id = 10089;
    newUser.username = '宇';
    newUser.password = '1234567a';
    newUser.portrait = 'https://pics2.baidu.com/feed/c8177f3e6709c93dbe2dd0f83164afdbd0005447.jpeg?token=ab92b7be38319ee23e7285e7725f08e4';
    newUser.email = '975155171@qq.com';
    newUser.nickname = '天上玥';
    newUser.article_num = 0;
    return await this.userRepository.save(newUser);
  }

  // 登录
  async login(createUser: LoginDto) {
    const userSql = `WHERE user_tel LIKE "%${ createUser.username }%"`;
    const user = await this.userRepository.query(`SELECT * FROM user ${ userSql }`);
    const payload = { sub: user.user_id };
    return {
      token: this.JwtService.sign(payload)
    };
  }

  // 获取用户信息
  async admin_info() {
    return {
      "userId":"1",
      "username":"admin",
      "realName":"Admin",
      "avatar":"",
      "desc":"manager",
      "password":"",
      "token":"",
      "permissions":[
        {
            "label":"主控台",
            "value":"dashboard_console"
        },
        {
            "label":"监控页",
            "value":"dashboard_monitor"
        },
        {
            "label":"工作台",
            "value":"dashboard_workplace"
        },
        {
            "label":"基础列表",
            "value":"basic_list"
        },
        {
            "label":"基础列表删除",
            "value":"basic_list_delete"
        }
      ]
    };
  }

  findAll(): Promise<User[]> {
    return this.userRepository.find()
  }

  // findOne(id: string): Promise<User> {
  //   return this.userRepository.findOne(id)
  // }

  async remove(id: string): Promise<void> {
    await this.userRepository.delete(id)
  }
}
